import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';
import router from '../router';

axios.defaults.baseURL = 'http://localhost:7777/'

const service: AxiosInstance = axios.create({
    timeout: 5000
});

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        console.log(config.auth)
        if (config.url === '/security/oauth/token') {
            config.headers['Content-type'] = 'application/x-www-form-urlencoded'
        } else {
            config.headers['Authorization'] = localStorage.getItem('Authorization')
            config.headers['Content-type'] = 'application/json; charset=UTF-8'
        }
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    (response: AxiosResponse) => {
        // 对响应数据做点什么
        console.log(response)
        console.log(response.data)
        console.log(response.headers)
        const data = response.data
        if (data.access_token) {
            localStorage.setItem('Authorization',data.token_type+' '+data.access_token)
        } else if (!data.success) {
            if (data.info.indexOf('token') > -1) {
                ElMessage.error('登录状态失效，请重新登录！');
                router.replace('/login')
                localStorage.removeItem('Authorization');
            } else {
                ElMessage.error(data.info);
            }
        }
        if (response.headers.token) {
            localStorage.setItem('Authorization', response.headers.token)
        }
        return response
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

export default service;
